//
//  UIButton+Click.m
//  Pods
//
//  Created by 刘 真 on 4/22/16.
//
//

#import "UIButton+Click.h"
#import <JRSwizzle/JRSwizzle.h>
#import "ClickAnalysis.h"

@import UIKit;
@import CoreGraphics;

@implementation UIButton (Click)

+ (void)load {
    [UIButton jr_swizzleMethod:@selector(sendAction:to:forEvent:)
                    withMethod:@selector(swizzle_sendAction:to:forEvent:)
                         error:nil];
}

- (UIViewController *)parentController {
    UIResponder *r = self;
    while (r && ![r isKindOfClass:[UIViewController class]]) {
        r = [r nextResponder];
    }
    return (UIViewController *)r;
}

- (void)swizzle_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {

    [self swizzle_sendAction:action to:target forEvent:event];
    
    UIViewController *c = [self parentController];
    
    if ([c isKindOfClass:[UINavigationController class]]) {
        UINavigationController *n = (UINavigationController *)c;
        c = [n visibleViewController];
    }
    
    if ([ClickAnalysis sharedAnalysis].handler) {
        [ClickAnalysis sharedAnalysis].handler(c, [self titleForState:UIControlStateNormal]);
    }
}


@end
